package com.css.dzj.zfjg.modules.statisticsa.service.impl;

import com.css.dzj.zfjg.common.util.excel.ExcelUtil;
import com.css.dzj.zfjg.modules.statisticsa.entity.QStatisticsa;
import com.css.dzj.zfjg.modules.statisticsa.entity.Statisticsa;
import com.css.dzj.zfjg.modules.statisticsa.mapper.StatisticsaMapper;
import com.css.dzj.zfjg.modules.statisticsa.service.StatisticsaService;
import com.css.dzj.zfjg.modules.statisticsb.entity.Statisticsb;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

@Service
public class StatisticsaServiceImpl implements StatisticsaService {
    @Autowired
    private StatisticsaMapper statisticsaMapper;
    @Autowired
    private JPAQueryFactory jpaQueryFactory;

    @Override
    public void add(Statisticsa statisticsa) {
        if (statisticsa == null) {
            throw new RuntimeException("实体为空！");
        }
        statisticsaMapper.save(statisticsa);
    }

    @Override
    public void addFromExcel(MultipartFile file) throws Exception {
        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();
        // 获取文件类型
        String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        // 从第一行开始读取
        Integer startRows = 1;
        // 获取输入流
        InputStream is = file.getInputStream();
        // Excel导入导出的单元类
        List<String[]> strings = ExcelUtil.readData(fileType, startRows, true, is);
        // Excel行数据重复
        String address = this.lineRepeat(strings);
        if (address != null) {
            throw new RuntimeException("行重复:" + address + "!");
        }
        for (String[] s : strings) {
            // 将字符串数组数据转换为实体,并且向数据库添加实体数据
            Statisticsa statisticsa = castStatisticsa(s);
            // 省市县重复时，覆盖原有数据
            Statisticsa statisticsaOld = queryIdByArea(s[0], s[1], s[2]);
            if (statisticsaOld != null) {
                statisticsa.setId(statisticsaOld.getId());
            }
            statisticsaMapper.save(statisticsa);
        }
    }

    /**
     * 判断是否有重复行，返回重复数据
     *
     * @param strings
     * @return
     */
    private String lineRepeat(List<String[]> strings) {
        HashSet<String> set = new HashSet<>();
        for (String[] s : strings) {
            String address = s[0] + s[1] + s[2];
            if (set.contains(address)) {
                return address;
            }
            set.add(address);
        }
        return null;
    }

    /**
     * 根据省市县(三者一块是惟一的)查找库数据
     *
     * @param provincial
     * @param municipallevel
     * @param countylevel
     * @return
     */
    private Statisticsa queryIdByArea(String provincial, String municipallevel, String countylevel) {
        QStatisticsa q = QStatisticsa.statisticsa;
        return jpaQueryFactory.selectFrom(q)
                .where(q.provincial.eq(provincial), q.municipalLevel.eq(municipallevel), q.countyLevel.eq(countylevel))
                .fetchOne();
    }

    /**
     * 转换实体
     *
     * @param s
     * @return
     */
    private Statisticsa castStatisticsa(String[] s) {
        Statisticsa statisticsa = new Statisticsa();
        /**
         * 设置excel表格对应的必填字段
         */
        try {
            // 省、市、县级
            statisticsa.setProvincial(s[0]);
            statisticsa.setMunicipalLevel(s[1]);
            statisticsa.setCountyLevel(s[2]);
            // 国标一、二、三级行业名称
            statisticsa.setNationalStandard1Name(s[3]);
            statisticsa.setNationalStandard2Name(s[4]);
            statisticsa.setNationalStandard3Name(s[5]);
            // 国办信用分级标准 A-E 类企业个数
            statisticsa.setNationalStandardANumber(s[6]);
            statisticsa.setNationalStandardBNumber(s[7]);
            statisticsa.setNationalStandardCNumber(s[8]);
            statisticsa.setNationalStandardDNumber(s[9]);
            statisticsa.setNationalStandardENumber(s[10]);
            // 国办信用分级标准无评级企业个数
            statisticsa.setNationalStandardNoNumber(s[11]);
            // 国办信用分级标准A~E 类企业总个数
            statisticsa.setNationalStandardAENumber(s[12]);
            // 国办信用分级标准较上月信用分类上升、下降企业个数
            statisticsa.setNationalStandardCreditRiseNumber(s[13]);
            statisticsa.setNationalStandardCreditDeclineNumber(s[14]);
            // 国办信用分级标准 A->E 类企业比例
            statisticsa.setNationalStandardAProportion(s[15]);
            statisticsa.setNationalStandardBProportion(s[16]);
            statisticsa.setNationalStandardCProportion(s[17]);
            statisticsa.setNationalStandardDProportion(s[18]);
            statisticsa.setNationalStandardEProportion(s[19]);
            // 国办信用分级标准较上月信用分类上升、下降企业比例
            statisticsa.setNationalStandardCreditRiseProportion(s[20]);
            statisticsa.setNationalStandardCreditDeclineProportion(s[21]);
        } catch (ArrayIndexOutOfBoundsException e) {
            throw new RuntimeException("表中缺少一列或多列！");
        }
        return statisticsa;
    }
}
